<template>
	<el-main class="bg table_wrap">
		<!-- 文件上传区域 -->
		<el-card shadow="hover" style="margin-bottom: 20px;">
			<div slot="header">
				<span>文件上传管理</span>
			</div>
			<el-upload
				class="upload-demo"
				drag
				:action="uploadUrl"
				:headers="uploadHeaders"
				:on-success="handleUploadSuccess"
				:on-error="handleUploadError"
				:on-progress="handleProgress"
				:before-upload="beforeUpload"
				:file-list="[]"
				multiple
				:auto-upload="true">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<div class="el-upload__tip" slot="tip">支持上传图片、文档、压缩包等文件，单个文件不超过10MB。上传的文件将自动保存到系统中。</div>
			</el-upload>
		</el-card>

		<!-- 搜索表单 -->
		<el-form label-position="right" :model="query" class="form p_4" label-width="120">
			<el-row>
				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="文件名">
						<el-input v-model="query.name"></el-input>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
					<el-form-item label="文件类型">
						<el-select v-model="query.type" placeholder="请选择" clearable>
							<el-option label="图片" value="image"></el-option>
							<el-option label="文档" value="document"></el-option>
							<el-option label="压缩包" value="archive"></el-option>
							<el-option label="其他" value="other"></el-option>
						</el-select>
					</el-form-item>
				</el-col>

				<el-col :xs="24" :sm="24" :lg="24" class="search_btn_wrap">
					<el-col :xs="24" :sm="12" :lg="12" class="search_btn_1">
						<el-form-item>
							<el-button type="primary" @click="search()" class="search_btn_find">查询</el-button>
							<el-button @click="reset()" class="search_btn_reset">重置</el-button>
						</el-form-item>
					</el-col>

					<el-col :xs="24" :sm="12" :lg="12" class="search_btn_2">
						<el-form-item>
							<el-button v-if="user_group == '管理员' || $check_action('/upload/table','del')" class="float-right search_btn_del" type="danger" @click="delInfo()">删除</el-button>
						</el-form-item>
					</el-col>
				</el-col>
			</el-row>
		</el-form>
		
		<!-- 数据表格 -->
		<el-table border :data="list" @selection-change="selectionChange" @sort-change="$sortChange" style="width: 100%" stripe>
			<el-table-column fixed type="selection" tooltip-effect="dark" width="50">
			</el-table-column>

			<el-table-column prop="name" label="文件名" min-width="200">
			</el-table-column>

			<el-table-column prop="type" label="文件类型" min-width="120">
				<template slot-scope="scope">
					<el-tag :type="getFileTypeTag(scope.row.type)">
						{{ getFileTypeName(scope.row.type) }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="path" label="文件路径" min-width="200">
				<template slot-scope="scope">
					<a :href="$fullUrl(scope.row.path)" target="_blank" style="color: #409EFF;">
						{{ scope.row.path }}
					</a>
				</template>
			</el-table-column>

			<el-table-column prop="file" label="预览" min-width="150" v-if="isImageType">
				<template slot-scope="scope">
					<el-image
						v-if="isImage(scope.row.path)"
						style="width: 100px; height: 100px"
						:src="$fullUrl(scope.row.path)"
						:preview-src-list="[$fullUrl(scope.row.path)]">
						<div slot="error" class="image-slot">
							<img src="/img/error.png" style="width: 90px; height: 90px" />
						</div>
					</el-image>
					<span v-else>-</span>
				</template>
			</el-table-column>

			<el-table-column prop="display" label="显示顺序" min-width="100">
			</el-table-column>

			<el-table-column prop="dir" label="所属目录" min-width="150">
			</el-table-column>

			<!-- 操作 -->
			<el-table-column fixed="right" label="操作" width="200">
				<template slot-scope="scope">
					<el-button 
						v-if="user_group == '管理员' || $check_action('/upload/table','set')" 
						type="primary" 
						size="small" 
						@click="downloadFile(scope.row)">
						下载
					</el-button>
					<el-button 
						v-if="user_group == '管理员' || $check_action('/upload/table','set')" 
						type="success" 
						size="small" 
						@click="copyLink(scope.row)">
						复制链接
					</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!-- 分页器 -->
		<div class="mt text_center">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="query.page"
			 :page-sizes="[7, 10, 30, 100]" :page-size="query.size" layout="total, sizes, prev, pager, next, jumper" :total="count">
			</el-pagination>
		</div>
		<!-- /分页器 -->
	</el-main>
</template>

<script>
	import mixin from "@/mixins/page.js";

	export default {
		mixins: [mixin],
		data() {
			return {
				// 获取数据地址
				url_get_list: "~/api/upload/get_list?like=0",
				url_del: "~/api/upload/del?",
				url_upload: "~/api/upload/upload?",

				// 字段ID
				field:"upload_id",

				// 查询
				query: {
					size: 10,
					page: 1,
					name: "",
					type: "",
				},

				// 数据
				list: [],
				
				// 上传相关
				fileList: [],
				uploadUrl: '',
				uploadHeaders: {}
			}
		},
		computed: {
			isImageType() {
				return this.list.some(item => this.isImage(item.path));
			}
		},
		methods: {
			deleteRow(index, rows) {
				rows.splice(index, 1);
			},

			table_class({row, column, rowIndex, columnIndex}){
				return "table_class";
			},
			
			/**
			 * 判断是否为图片
			 */
			isImage(path) {
				if (!path) return false;
				const imageExts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
				const lowerPath = path.toLowerCase();
				return imageExts.some(ext => lowerPath.endsWith(ext));
			},
			
			/**
			 * 获取文件类型标签
			 */
			getFileTypeTag(type) {
				const typeMap = {
					'image': 'success',
					'document': 'primary',
					'archive': 'warning',
					'other': 'info'
				};
				return typeMap[type] || 'info';
			},
			
			/**
			 * 获取文件类型名称
			 */
			getFileTypeName(type) {
				const nameMap = {
					'image': '图片',
					'document': '文档',
					'archive': '压缩包',
					'other': '其他'
				};
				return nameMap[type] || type || '未知';
			},
			
			/**
			 * 上传前验证
			 */
			beforeUpload(file) {
				const isLt10M = file.size / 1024 / 1024 < 10;
				if (!isLt10M) {
					this.$message.error('上传文件大小不能超过 10MB!');
				}
				return isLt10M;
			},
			
			/**
			 * 上传成功回调
			 */
			handleUploadSuccess(response, file, fileList) {
				if (response.result && response.result.url) {
					this.$message.success('文件上传成功！');
					// 将上传的文件信息保存到数据库
					this.saveUploadRecord(file, response.result.url);
					// 刷新列表
					this.get_list();
				} else {
					this.$message.error(response.error?.message || '上传失败');
				}
			},
			
			/**
			 * 保存上传记录到数据库
			 */
			async saveUploadRecord(file, url) {
				try {
					// 根据文件扩展名判断文件类型
					const ext = file.name.split('.').pop().toLowerCase();
					let fileType = 'other';
					if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
						fileType = 'image';
					} else if (['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'txt'].includes(ext)) {
						fileType = 'document';
					} else if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
						fileType = 'archive';
					}
					
					const uploadData = {
						name: file.name,
						path: url,
						file: url,
						type: fileType,
						display: '0',
						dir: '/'
					};
					
					const result = await this.$post("~/api/upload/add?", uploadData);
					if (result.result) {
						console.log('上传记录已保存');
					} else {
						console.error('保存上传记录失败:', result.error);
					}
				} catch (error) {
					console.error('保存上传记录出错:', error);
				}
			},
			
			/**
			 * 上传失败回调
			 */
			handleUploadError(err, file, fileList) {
				this.$message.error('文件上传失败！');
				console.error('上传失败:', err);
			},
			
			/**
			 * 上传进度回调
			 */
			handleProgress(event, file, fileList) {
				// 可以在这里显示上传进度
			},
			
			/**
			 * 下载文件
			 */
			downloadFile(row) {
				if (row.path) {
					const url = this.$fullUrl(row.path);
					window.open(url, '_blank');
				}
			},
			
			/**
			 * 复制文件链接
			 */
			copyLink(row) {
				if (row.path) {
					const url = this.$fullUrl(row.path);
					// 创建临时input元素
					const input = document.createElement('input');
					input.value = url;
					document.body.appendChild(input);
					input.select();
					document.execCommand('copy');
					document.body.removeChild(input);
					this.$message.success('链接已复制到剪贴板');
				}
			}
		},
		mounted() {
			// 设置上传URL和请求头
			const token = this.$store.state.user.token || $.db.get("token");
			this.uploadUrl = this.url_upload.replace('~/', '');
			if (token) {
				this.uploadHeaders = {
					'Authorization': 'Bearer ' + token
				};
			}
			// 确保数据从后端获取
			this.get_list();
		}
	}
</script>

<style type="text/css">
	.upload-demo {
		width: 100%;
	}
	
	.upload-demo >>> .el-upload-dragger {
		width: 100%;
	}
</style>
